package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.Result;
import com.itheima.entity.Article;
import com.itheima.entity.Category;
import com.itheima.service.IArticleService;
import com.itheima.vo.PageBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yancy
 * @since 2024-03-07
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleService;

    @PostMapping
    public Result add(@RequestBody @Validated(Article.Add.class) Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleService.save(article);
        return Result.ok();
    }

    @GetMapping
    public Result<PageBean<Article>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state
    ) {
        PageBean<Article> pb =  articleService.pageList(pageNum,pageSize,categoryId,state);
        return Result.ok(pb);
    }

//    @GetMapping
//    public Result<IPage<Article>> list(Integer pageNum,
//            Integer pageSize,
//            @RequestParam(required = false) Integer categoryId,
//            @RequestParam(required = false) String state){
//        Page<Article> page = new Page<>(pageNum, pageSize);
//        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
//        if (categoryId != null){
//            queryWrapper.eq("category_id",categoryId);
//        }
//        if (StringUtils.isNotBlank(state)){
//            queryWrapper.like("state",state);
//        }
//        IPage<Article> articlePage = articleService.page(page, queryWrapper);
//        return Result.ok(articlePage);
//    }
    @GetMapping("/detail")
    public Result<Article> detail(Integer id){
        Article c = articleService.getById(id);
        return Result.ok(c);
    }
    @PutMapping
    public Result update(@RequestBody @Validated(Article.Update.class) Article article) {
        articleService.updateById(article);
        return Result.ok();
    }
    @DeleteMapping
    public Result delete(String id) {
        articleService.removeById(id);
        return Result.ok();
    }
}

